//
//  SocketUtils.swift
//  SmartCheckIn
//
//  Created by Cidy Chou on 2017/8/29.
//  Copyright © 2017年 CidyChou. All rights reserved.
//

import Foundation



class SocketUtils{

    //socket客户端类对象
    var socketClient:TCPClient?
    var byteResFrame:[UInt8]
    
    init(bytes : [UInt8] , serverArr: [Any]) {
        self.byteResFrame = bytes
        
     //[dm.gdsdxy.cn, 9985, 5, 8085, 210.21.85.178, 广东水利电力职业学院, 5]
        //4.21
        let serverIP = serverArr[0] as! String
        let serverPort = Int(serverArr[1 ] as! String)
        print("socket:\(serverArr)")
        
        socketClient=TCPClient(addr: serverIP, port: serverPort!)
        
    }
    
    
    ///初始化客户端，并连接服务器 
//    func getResult() -> Int {
//        // 01 成功， 02 失败
//        var ACKResult : Int
//        
//        loadData {(res) -> () in
//            ACKResult = res
//        }
//        
//        return ACKResult
//    }

    
    func loadData(finish : @escaping (_ res:Int)->())  {
        //qos 优先级  .background 最低
        DispatchQueue.global(qos: .background).async {
            
            //用于读取并解析服务端发来的
            func readmsg()->[UInt8]?{
                //read 4 byte int as type
                if let data=self.socketClient!.read(10){
                    print("data:\(data)")
                    //self.socketClient?.close()
                    return data
                }
                return nil
            }
            
            //连接服务器
            let (success,_)=self.socketClient!.connect(timeout: 5)
            if success{
                DispatchQueue.main.async {
                    print("------------------------")
                    print("连接成功，正在匹配.....")
                    print("------------------------")                }
                _ = self.socketClient!.send(data:self.byteResFrame)//发送信息
                //不断接收服务器发来的消息
                while true{
                    if let msg=readmsg(){
                        DispatchQueue.main.async {
                            finish(self.processMessage(msg: msg))
                        }
                        break
                    }else{
                        DispatchQueue.main.async {
                            finish(2)
                            //self.socketClient?.close()
                            //ACKResult = 2 //失败
                        }
                        break
                    }
                }
            }else{
                DispatchQueue.main.async {
                    finish(2)
                }
            }
        }

    }
    
    
    
    //处理服务器返回的消息
    func processMessage(msg:[UInt8]) -> Int{
        //print("msg:\(Int(msg[5]))")
        return Int(msg[5])
    }
}
